﻿using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using CustomFtpLib;
using CustomIniLib;

namespace FtpApplication
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {

        }
        private void Window_Load(object sender, RoutedEventArgs e)
        {
            //Fresh_Click(null, null);
        }
        private bool CheckInputIP()
        {
            try
            {
                IPAddress ipTry = IPAddress.Parse(this.ServerIP.Text);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private string GetItemPath(TreeViewItem SelectedItem)
        {
            string ret = SelectedItem.Header.ToString();
            if (ret == "根目录")
                return "";
            TreeViewItem lastCheckItem = SelectedItem;
            while (true)
            {
                TreeViewItem parentItem = lastCheckItem.Parent as TreeViewItem;
                if (parentItem != null && parentItem.Header.ToString() != "根目录")
                {
                    ret = parentItem.Header.ToString() + "/" + ret;
                    lastCheckItem = parentItem;
                }
                else
                    break;
            }
            return ret;
        }
        private TreeViewItem GenerateSubTree(string rootItemName)
        {
            TreeViewItem rootItem = null;
            int index = rootItemName.LastIndexOf('/');
            if (index != -1)
                rootItem = new TreeViewItem { Header = rootItemName .Substring(index + 1) };
            else
                rootItem = new TreeViewItem { Header = rootItemName };
            FtpHelper tempFtpHelper = new FtpHelper(this.ServerIP.Text, rootItemName, UserName.Text, PassWord.Password);
            string[] subDirlist = tempFtpHelper.GetDirectoryList();
            if (subDirlist.Length != 0)
            {
                foreach (string sublistItem in subDirlist)
                {
                    rootItem.Items.Add(GenerateSubTree(rootItemName + "/" + sublistItem));
                }
            }
            string[] subFilelist = tempFtpHelper.GetFileList();
            foreach (string subFilelistItem in subFilelist)
            {
                TreeViewItem tempFileItem = new TreeViewItem { Header = subFilelistItem };
                rootItem.Items.Add(tempFileItem);
            }
            return rootItem;
        }
        private void UploadFile_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckInputIP())
            {
                System.Windows.Forms.MessageBox.Show("请输入正确的IP地址：(0-255).(0-255).(0-255).(0-255)", "提示");
                return;
            }
            if (this.LocalFile.Text == string.Empty || !File.Exists(this.LocalFile.Text))
            {
                System.Windows.Forms.MessageBox.Show("请选择文件！", "提示");
                return;
            }
            FtpHelper ftpHelper = new FtpHelper(this.ServerIP.Text, "", UserName.Text, PassWord.Password);
            TreeViewItem selectedItem = contentsOnFtpServer.SelectedItem as TreeViewItem;
            string objPathOnServer = GetItemPath(selectedItem);
            string ret = ftpHelper.UploadFile(this.LocalFile.Text, objPathOnServer, false);
            if (ret.StartsWith("done"))
            {
                FileInfo fileInfo = new FileInfo(this.LocalFile.Text);
                TreeViewItem newItem = new TreeViewItem { Header = fileInfo.Name };
                selectedItem.Items.Add((newItem));
                System.Windows.MessageBox.Show("上传成功！", "提示");
            }
            else
                System.Windows.MessageBox.Show("上传失败！\n" + ret, "提示");
        }
        private void SelectFile_Click(object sender, RoutedEventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "c:\\";
                openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                openFileDialog.FilterIndex = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == (DialogResult)1)
                {
                    string filePath = openFileDialog.FileName;
                    this.LocalFile.Text = filePath;
                }
            }
        }
        private void DownloadFile_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckInputIP())
            {
                System.Windows.Forms.MessageBox.Show("请输入正确的IP地址：(0-255).(0-255).(0-255).(0-255)", "提示");
                return;
            }
            if (DownloadPath.Text == string.Empty)
            {
                System.Windows.MessageBox.Show("请选择文件保存路径!");
                return;
            }
            TreeViewItem selectedItem = contentsOnFtpServer.SelectedItem as TreeViewItem;
            string objFileName = DownloadPath.Text + @"\" + selectedItem.Header.ToString();
            if (File.Exists(objFileName))
            {
                System.Windows.MessageBox.Show("文件已存在！\n" + objFileName);
                return;
            }
            string filePathOnServer = GetItemPath(selectedItem);
            FtpHelper ftpHelper = new FtpHelper(this.ServerIP.Text, "", UserName.Text, PassWord.Password);
            string ret = ftpHelper.DownloadFile(filePathOnServer, objFileName);

            if (ret.StartsWith("done"))
                System.Windows.MessageBox.Show("下载成功！", "提示");
            else
                System.Windows.MessageBox.Show("下载失败！\n" + ret, "提示");
        }

        private void Fresh_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckInputIP())
            {
                System.Windows.Forms.MessageBox.Show("请输入正确的IP地址：(0-255).(0-255).(0-255).(0-255)", "提示");
                return;
            }
            if (UserName.Text.Length == 0 || PassWord.Password.Length == 0)
            {
                System.Windows.Forms.MessageBox.Show("用户名或密码为空！", "提示");
                return;
            }
            
            TreeViewItem rootItem = new TreeViewItem { Header = "根目录" };
            
            FtpHelper ftpHelper = new FtpHelper(this.ServerIP.Text, "", UserName.Text, PassWord.Password);
            string[] FoldersFind = ftpHelper.GetDirectoryList();
            if (FoldersFind.Length != 0)//文件夹使用递归方法进行遍历，直至文件夹数量为0
            {
                foreach (string Folder in FoldersFind)
                {
                    TreeViewItem treeViewItem = GenerateSubTree(Folder);
                    rootItem.Items.Add(treeViewItem);
                }
            }
            string[] FilesFind = ftpHelper.GetFileList();
            if (FilesFind.Length != 0)
            {
                foreach (string File in FilesFind)
                {
                    TreeViewItem treeViewItem = new TreeViewItem { Header = File};
                    rootItem.Items.Add(treeViewItem);
                }
            }
            contentsOnFtpServer.Items.Clear();//先清空treeView
            contentsOnFtpServer.Items.Add(rootItem);
        }

        private void ServerIP_Changed(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (ServerIP.Text.Length > 15)
            {
                System.Windows.MessageBox.Show("已超过ip地址最大长度，请重新输入！", "提示");
                ServerIP.Text = "";
            }
        }

        private void SelectSavePath_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                return;
            DownloadPath.Text = folderBrowserDialog.SelectedPath;
        }

        private void DeleteSelectedFile_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckInputIP())
            {
                System.Windows.Forms.MessageBox.Show("请输入正确的IP地址：(0-255).(0-255).(0-255).(0-255)", "提示");
                return;
            }
            if (UserName.Text.Length == 0 || PassWord.Password.Length == 0)
            {
                System.Windows.Forms.MessageBox.Show("用户名或密码为空！", "提示");
                return;
            }
            TreeViewItem selectedItem = contentsOnFtpServer.SelectedItem as TreeViewItem;
            string filePathOnServer = GetItemPath(selectedItem);
            FtpHelper ftpHelper = new FtpHelper(this.ServerIP.Text, "", UserName.Text, PassWord.Password);
            string ret = ftpHelper.deleteFile(filePathOnServer);

            System.Windows.MessageBox.Show(ret, "提示");
            if (ret.StartsWith("done"))
            {
                TreeViewItem parentdItem = selectedItem.Parent as TreeViewItem;
                parentdItem.Items.Remove(selectedItem);
            }
        }
    }
}
